﻿// -------------------------------------------------------------------------------
// 
// This file is part of the FluidKit project: http://www.codeplex.com/fluidkit
// 
// Copyright (c) 2008, The FluidKit community 
// All rights reserved.
// 
// Redistribution and use in source and binary forms, with or without modification, 
// are permitted provided that the following conditions are met:
// 
// * Redistributions of source code must retain the above copyright notice, this 
// list of conditions and the following disclaimer.
// 
// * Redistributions in binary form must reproduce the above copyright notice, this 
// list of conditions and the following disclaimer in the documentation and/or 
// other materials provided with the distribution.
// 
// * Neither the name of FluidKit nor the names of its contributors may be used to 
// endorse or promote products derived from this software without specific prior 
// written permission.
// 
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR 
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
// -------------------------------------------------------------------------------
using System;
using System.Diagnostics;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using FluidKit.Controls;
using MbWsClient;
using MbWsClient.Classes;
using System.Threading;
using System.Windows.Threading;
using MbWsClient.Service.Enums;
using MbWsClient.ServiceClasses;

namespace FluidKit.Showcase.ElementFlow
{
	/// <summary>
	/// Interaction logic for Window1.xaml
	/// </summary>
	public partial class Window1
	{
		private StringCollection _dataSource;
		private Random _randomizer = new Random();
        private CollectionItem _currentCollection;

		private int _viewIndex;

		private LayoutBase[] _layouts = {
											new Wall(),
											new SlideDeck(),
											new CoverFlow(),
											new Carousel(),
											new TimeMachine2(),
											new ThreeLane(),
											new VForm(),
											new TimeMachine(),
											new RollerCoaster(),
											new Rolodex(),
		                                 };

		public Window1()
		{
			InitializeComponent();
			Loaded += Window1_Loaded;
		}

		private void Window1_Loaded(object sender, RoutedEventArgs e)
		{
			_elementFlow.Layout = _layouts[0];
			_currentViewText.Text = _elementFlow.Layout.GetType().Name;

			_elementFlow.SelectedIndexChanged += EFSelectedIndexChanged;
			_elementFlow.SelectedIndex = 0;

            _dataSource = FindResource("TestDataSource") as StringCollection;

            var startUpFolders = ItemRepository.StartupFolders();
            AddItems(startUpFolders);

            _selectedIndexSlider.Maximum = _elementFlow.Items.Count - 1;
		}

        private void AddItems(CollectionItem item)
        {
            _dataSource.Clear();
            _currentCollection = item;
            foreach (var element in item.Children)
            {
                //ThreadPool.QueueUserWorkItem(o =>
                //{
                    var child = ItemRepository.GetItem(element);
                    string image = child.ImageDictionary.GetImage(ImageTypes.PrimaryImage);
                    if (!string.IsNullOrEmpty(image))
                    {
                        _dataSource.Add(image);
                        //Dispatcher.Invoke(DispatcherPriority.Input, new ThreadStart(() => { _dataSource.Add(image); }));
                    }
                //});
            }
            _elementFlow.SelectedIndex = item.LastSelectedIndex;
            UpdateName(item.LastSelectedIndex);
        }

		private void EFSelectedIndexChanged(object sender, EventArgs e)
		{
			int selectedIndex = (sender as FluidKit.Controls.ElementFlow).SelectedIndex;
            UpdateName(selectedIndex);
		}

        private void UpdateName(int selectedIndex)
        {
            if (_dataSource != null && _dataSource.Count > selectedIndex && selectedIndex >= 0)
            {
                _currentSelectedItemName.Text = _currentCollection.Children.ElementAt(selectedIndex).Name;
                _currentCollection.LastSelectedIndex = selectedIndex;
            }
        }

		protected override void OnKeyDown(KeyEventArgs e)
		{
            if (!e.Handled)
            {
                if (e.Key == Key.F12)
                {
                    _viewIndex = (_viewIndex + 1) % _layouts.Length;
                    _elementFlow.Layout = _layouts[_viewIndex];
                    _currentViewText.Text = _elementFlow.Layout.GetType().Name;
                }
                else if (e.Key == Key.Enter)
                {
                    int selectedIndex = _elementFlow.SelectedIndex;
                    BasicItem currItem = _currentCollection.Children.ElementAt(selectedIndex);
                    if (currItem.Type == MediaTypes.Movie ||
                        currItem.Type == MediaTypes.Episode)
                    {
                        AppSettings.MbService.PlayItem(currItem.Id);
                    }
                    else
                    {
                        Item item = ItemRepository.GetNextItem(currItem);
                        CollectionItem collection = item as CollectionItem;
                        if (collection != null)
                        {
                            AddItems(collection);
                        }
                    }

                }
                else if (e.Key == Key.Back)
                {
                    CollectionItem currItem = _currentCollection;
                    Item item = ItemRepository.GetPreviousItem();
                    CollectionItem collection = item as CollectionItem;
                    if (collection != null)
                    {
                        AddItems(collection);
                    }
                }
                else if (e.Key == Key.F5)
                {
                    ItemRepository.ClearCache(_currentCollection);
                    AddItems((CollectionItem)ItemRepository.GetItem(_currentCollection));
                }
                else if (e.Key == Key.P)
                {
                    Thread.Sleep(TimeSpan.FromSeconds(10));
                    AppSettings.MbService.SendCommand(CommandTypes.Pause);
                }
                else if (e.Key == Key.S)
                {
                    AppSettings.MbService.SendCommand(CommandTypes.Stop);
                }
                else if (e.Key == Key.F)
                {
                    AppSettings.MbService.SendCommand(CommandTypes.FastForward);
                }
                else if (e.Key == Key.B)
                {
                    AppSettings.MbService.SendCommand(CommandTypes.Rewind);
                }
            }
		}

		private void ChangeSelectedIndex(object sender, RoutedPropertyChangedEventArgs<double> args)
		{
			_elementFlow.SelectedIndex = (int)args.NewValue;
		}
	}
}